package architecture.view;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class LoginDialog extends JDialog {
	private MainForm mainForm;
	private JLabel lblName, lblPass;
	private JTextField txtName;
	private JPasswordField txtPass;
	private JButton btnLogin, btnCancel;

	public LoginDialog(MainForm mainForm, boolean value) {
		super(mainForm.getMainForm(), value);
		this.mainForm = mainForm;
		setTitle("Login");
		setSize(330, 98);
		setLocationRelativeTo(mainForm.getMainForm());
		setLayout(new GridLayout(3, 2));
		setResizable(false);
		initComponents();
	}

	private void initComponents() {
		lblName = new JLabel("Login Name:");
		lblPass = new JLabel("Password:");
		txtName = new JTextField();
		txtPass = new JPasswordField();
		btnLogin = new JButton("Log in");
		btnCancel = new JButton("Cancel");

		btnLogin.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				if (txtName.getText().compareTo("") == 0)
					{
						JOptionPane.showMessageDialog(mainForm.getLoginDialog(),
							"Insert username!", "Warning",
							JOptionPane.WARNING_MESSAGE);
					txtName.requestFocus();
					}
				else if (txtPass.getText().compareTo("") == 0)
					{
						JOptionPane.showMessageDialog(mainForm.getLoginDialog(),
							"Insert password!", "Warning",
							JOptionPane.WARNING_MESSAGE);
						txtPass.requestFocus();
					}
				else if (txtPass.getText().equals(
						mainForm.getDatabase()
								.getPassForUser(txtName.getText()))) {
					mainForm.logInAsUser(txtName.getText(), txtPass.getText());
					txtPass.setText("");
					txtName.setName("");
					setVisible(false);
				} else {
					JOptionPane.showMessageDialog(mainForm.getLoginDialog(),
							"Invalid username or password!", "Warning",
							JOptionPane.WARNING_MESSAGE);
					txtName.selectAll();
					txtName.requestFocus();
					txtPass.setText("");
				}
			}

		});

		btnCancel.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				dispose();
			}

		});

		add(lblName);
		add(txtName);

		add(lblPass);
		add(txtPass);

		add(btnLogin);
		add(btnCancel);

	}
}
